package com.example.work;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class login extends Activity {
    private EditText userName;
    private EditText passWord;
    private EditText cardId;
    private Button LogBtn;
    static JSONObject inJson;
    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            if (msg.what == 0x123)
            {
            }
            else
            {
                Toast.makeText(login.this,
                        "网络错误", Toast.LENGTH_LONG)
                        .show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        userName = (EditText) findViewById(R.id.userName);
        passWord = (EditText) findViewById(R.id.passWord);
        cardId = (EditText) findViewById(R.id.cardId);
        LogBtn = (Button) findViewById(R.id.btn_Login);
        LogBtn.setEnabled(false);
        LogBtn.setBackgroundColor(Color.parseColor("#BBBBBB"));
        passWord.addTextChangedListener(editclick);
    }

    public void onclickRegister(View v){
        Intent intent=new Intent(login.this,MainActivity.class);
        startActivity(intent);
    }

    public void onclickNfc(View v){
        Intent intent=new Intent(login.this,NfcActivity.class);
        startActivity(intent);
    }

    public void onclick(View v)
    {
        new Thread(new Runnable(){
            @Override
            public void run() {
                String username = userName.getText().toString().trim();
                String password = passWord.getText().toString().trim();
                String cardIdStr = cardId.getText().toString().trim();
                if(username.isEmpty()||password.isEmpty()||cardIdStr.isEmpty())
                {
                    Looper.prepare();
                    Toast.makeText(login.this,
                            "账户名或密码或卡片id为空", Toast.LENGTH_LONG)
                            .show();
                    Looper.loop();
                    return;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("usr", username);
                map.put("pwd", password);
                map.put("id", cardIdStr);
                map.put("method", "login");
                String mapJson = JSON.toJSONString(map);
                String h = "http://175.178.90.31/loginServlet";
                URL netUrl = null;
                try {
                    netUrl = new URL(h);
                    String content = String.valueOf(mapJson);
                    HttpURLConnection conn = (HttpURLConnection) netUrl.openConnection();
                    conn.setDoOutput(true);// 设置允许输出
                    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    conn.setRequestProperty("Charset", "utf-8");
                    conn.setRequestMethod("POST");// 大写
                    OutputStream outputStream = conn.getOutputStream();
                    outputStream.write(content.getBytes());
                    if (conn.getResponseCode() == 200) {
                        handler.sendEmptyMessage(0x123);
                        InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "utf-8");
                        BufferedReader br = new BufferedReader(reader) ;
                        String result;
                        result = new String(br.readLine().getBytes());
                        inJson = JSONObject.parseObject(result);
                        Looper.prepare();
                        if (inJson.getString("usr").equals("NONE"))
                            Toast.makeText(login.this,
                                    "请检查用户名或是密码否正确", Toast.LENGTH_SHORT)
                                    .show();
                        else{
                            Toast.makeText(login.this,
                                    "欢迎你，"+inJson.getString("usr"), Toast.LENGTH_SHORT)
                                    .show();
                            Intent intent=new Intent(login.this,Main_Activity.class);
                            startActivity(intent);
                        }
                        Looper.loop();
                    }
                    else {
                        handler.sendEmptyMessage(0x122); }
                } catch (MalformedURLException | ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    private TextWatcher editclick = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {


        }


        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {


        }

        //一般我们都是在这个里面进行我们文本框的输入的判断，上面两个方法用到的很少
        @Override
        public void afterTextChanged(Editable s) {
            String pwd = passWord.getText().toString();
            Pattern p = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{3,16}$");
            Matcher m = p.matcher(pwd);
            if (m.matches()) {
                LogBtn.setEnabled(true);
                LogBtn.setBackgroundColor(Color.parseColor("#04BE02"));
            } else {
                LogBtn.setEnabled(false);
                LogBtn.setBackgroundColor(Color.parseColor("#BBBBBB"));
            }
        }
    };

}